package cn.ms.doctor.Controller;

import cn.ms.doctor.Entity.User;
import cn.ms.doctor.Resolver.GetSessionUserInter;
import cn.ms.doctor.Service.UserService;
import cn.ms.doctor.Utils.DataStandardUtils;
import cn.ms.doctor.Utils.GlobalMessage;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/User")
@Log4j2
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param request
     * @param params
     * @return
     */
    @RequestMapping("/NotLogin/UserByAccountAndPasswordAndRole")
    public Object getUserByAccountAndPasswordAndRole(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        //验证字段是否存在
        if (DataStandardUtils.standardKeyIsEmpty(params, "UserAccount", "UserPassword", "UserRole")) {
            return new GlobalMessage(200, 2, "非法请求", null);
        }
        //验证数据规范
        Map<String, Object> stringObjectMap = DataStandardUtils.standardLoginData(params);
        if (((boolean) stringObjectMap.get("result"))) {
            return new GlobalMessage(200, 1, stringObjectMap.get("value"), null);
        }
        //获取用户数据并存session
        HttpSession session = request.getSession();
        User user = userService.getUserByAccountAndPasswordAndRole(params);
        if (user == null) {
            return new GlobalMessage(200, 1, "账号密码输入错误", null);
        }
        session.setAttribute("userMsg", user);
        System.out.println(session.getId());
        return new GlobalMessage(200, 0, null, "登陆成功");
    }

    /**
     * 修改用户真实姓名
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/isLogin/UpUserNameByUserId", method = {RequestMethod.POST})
    public Object updateUserNameByUserId(@GetSessionUserInter User user,HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("UserName"))) {
            return new GlobalMessage(200, 2, "非法请求,请重新操作...", null);
        }
        if (DataStandardUtils.isNotRange(50, 2, String.valueOf(params.get("UserName")))) {
            return new GlobalMessage(200, 1, "姓名需要为2~50个字符内...", null);
        }
        if (StringUtils.endsWithIgnoreCase(user.getUserName(), String.valueOf(params.get("UserName")))) {
            return new GlobalMessage(200, 1, "您修改的真实姓名与上一次一致,请重新输入...", null);
        }
        if (!userService.updateUserNameByUserId(user.getUserId(), String.valueOf(params.get("UserName")))) {
            return new GlobalMessage(200, 3, "修改错误,请联系管理员查看问题...", null);
        }
        HttpSession session=request.getSession();
        session.invalidate();
        return new GlobalMessage(200, 0, null, "修改成功...");
    }

    /**
     * 修改密码
     *
     * @param user
     * @param params
     * @return
     */
    @RequestMapping(value = "/isLogin/UpUserPasswordByUserId", method = {RequestMethod.POST})
    public Object updateUserPasswordByUserId(@GetSessionUserInter User user,HttpServletRequest request, @RequestBody Map<String, Object> params) {
        //验证字段存在
        if (DataStandardUtils.standardKeyIsEmpty(params, "oldPassword", "newPassword")) {
            return new GlobalMessage(200, 2, "非法请求，请重新操作...", null);
        }
        //过滤数据
        if (DataStandardUtils.isNotRange(16, 5, params.get("oldPassword").toString(), params.get("newPassword").toString())) {
            return new GlobalMessage(200, 1, "密码大小为6~16位之间...", null);
        }
        //过滤是否有特殊字符
        if (DataStandardUtils.isPattern(DataStandardUtils.SPECIAL_CHARACTERS, params.get("oldPassword").toString(), params.get("newPassword").toString())) {
            return new GlobalMessage(200, 1, "禁止输入除了英文字母数字小数点以外的字符...", null);
        }
        //首字母大写
        if (!DataStandardUtils.isPattern(DataStandardUtils.TITLE_CASE, params.get("newPassword").toString())) {
            return new GlobalMessage(200, 1, "新密码首字母需要大写...", null);
        }
        //原密码是否输入正确
        if (!StringUtils.endsWithIgnoreCase(user.getUserPwd(), params.get("oldPassword").toString())) {
            return new GlobalMessage(200, 1, "输入的原密码不正确...", null);
        }
        //修改密码
        if (!userService.updateUserPasswordByUserId(user.getUserId(), params.get("newPassword").toString())) {
            return new GlobalMessage(200, 3, "修改失败,请联系管理员处理...", null);
        }
        HttpSession session=request.getSession();
        session.invalidate();
        return new GlobalMessage(200, 0, null, "修改成功...");
    }

    /**
     * 获取除了系统管理员外的所有用户
     *
     * @param params search:表示搜索内容为id，账号，真实姓名
     *               deptId:代表科室
     * @return
     */
    @RequestMapping("/isLogin/isSystemAdmin/getUsersBySelective")
    public Object getUsersBySelective(@RequestBody Map<String, Object> params) {
        if (DataStandardUtils.standardKeyIsEmpty(params, "pageIndex", "pageSize", "roleId")) {
            return new GlobalMessage(200, 2, "非法请求...", null);
        }
        Map<String, Object> data = userService.getUsersBySelective(params);
        return new GlobalMessage(200, 0, null, data);
    }

    /**
     * 修改科室，用户名，角色
     * @param params
     * @return
     */
    @RequestMapping("/isLogin/isSystemAdmin/updateUserDeptOrRoleOrName")
    public Object updateUserDeptORRoleOrName(@RequestBody Map<String, Object> params) {
        if (!DataStandardUtils.standardKeyIsEmpty(params, "newDeptId", "userId", "oldDeptId", "userAccount")) {
            if (DataStandardUtils.isPattern(DataStandardUtils.SPECIAL_CHARACTERS,
                    params.get("userAccount").toString(),
                    params.get("newDeptId").toString(),
                    params.get("userId").toString(),
                    params.get("oldDeptId").toString()
            )) {
                return new GlobalMessage(200, 1, "请不要传递特殊字符", null);
            }
        }else if(!DataStandardUtils.standardKeyIsEmpty(params, "newRoleId", "userId", "oldRoleId", "userAccount","newDeptId")){
            if (DataStandardUtils.isPattern(DataStandardUtils.SPECIAL_CHARACTERS,
                    params.get("userAccount").toString(),
                    String.valueOf(params.get("newRoleId")),
                    String.valueOf(params.get("userId")),
                    String.valueOf(params.get("oldRoleId")),
                    String.valueOf(params.get("newDeptId"))
            )) {
                return new GlobalMessage(200, 1, "请不要传递特殊字符", null);
            }
            System.out.println("字符过滤成功");
        }else if(!DataStandardUtils.standardKeyIsEmpty(params, "newUserName", "userId", "userAccount")){
            if (DataStandardUtils.isPattern(DataStandardUtils.SPECIAL_CHARACTERS,
                    params.get("userAccount").toString()
            )) {
                return new GlobalMessage(200, 1, "请不要传递特殊字符", null);
            }
            if (DataStandardUtils.isNotRange(30,1,params.get("newUserName").toString())) {
                return new GlobalMessage(200, 1, "真实姓名需要在2~30个字符之间", null);
            }
        } else {
            return new GlobalMessage(200, 2, "非法请求...", null);
        }
        System.out.println(JSON.toJSONString(params));
        if (!userService.updateRoleOrDeptOrName(params)) {
            return new GlobalMessage(200, 3, "出现异常请联系管理员查看...", null);
        }
        return new GlobalMessage(200, 0, null, "修改成功");

    }

    @RequestMapping("/isLogin/isSystemAdmin/deleteUserByUserIdAndAccount")
    public Object deleteUserByUserIdAndAccount(@RequestBody Map<String,Object> params){
        if (DataStandardUtils.standardKeyIsEmpty(params,"userId","userAccount")) {
            return new GlobalMessage(200,2,"非法请求...",null);
        }
        if (!userService.deleteUserByUserIdAndAccount(params)) {
            return new GlobalMessage(200,3,"出现异常请联系管理员处理...",null);
        }
        return new GlobalMessage(200,0,null,"删除成功...");
    }

    @RequestMapping("/isLogin/isSystemAdmin/addUser")
    public Object addUser(@RequestBody Map<String,Object> params){
        if(DataStandardUtils.standardKeyIsEmpty(params,"account","name","password","roleId","deptId")){
            return new GlobalMessage(200,0,"非法请求...",null);
        }
        if (DataStandardUtils.isNotRange(30,5,params.get("account").toString(),params.get("password").toString())) {
            return new GlobalMessage(200,1,"用户名密码需要在6~30位...",null);
        }
        if (DataStandardUtils.isPattern(DataStandardUtils.SPECIAL_CHARACTERS,
                params.get("account").toString(),
                params.get("password").toString(),
                params.get("roleId").toString(),
                params.get("deptId").toString()
        )) {
            return new GlobalMessage(200, 1, "请不要传递特殊字符...", null);
        }
        if (!DataStandardUtils.isPattern(DataStandardUtils.TITLE_CASE,params.get("password").toString())) {
            return new GlobalMessage(200, 1, "密码首字母需要大写...", null);
        }
        if (!userService.addUser(params)) {
            return new GlobalMessage(200, 3, "添加失败,请联系管理员处理...", null);
        }
        return new GlobalMessage(200,0,null,"添加成功...");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("/isLogin/loginOut")
    public Object loginOut(HttpServletRequest request){
        HttpSession session=request.getSession();
        session.invalidate();
        return new GlobalMessage(200,0,null,"注销成功");
    }

    /**
     * 获取登录数据
     * @param user
     * @return
     */
    @RequestMapping("/isLogin/loginMsg")
    public Object loginMsg(@GetSessionUserInter User user){

        return new GlobalMessage(200,0,null,user);
    }

}
